package com.xishu.controller;

import com.xishu.annotation.valid.MethodValidator;
import com.xishu.entity.shop.RunModel;
import com.xishu.entity.shop.Shop;
import com.xishu.response.ResponseData;
import com.xishu.response.ResponseStatus;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.RunModelService;
import com.xishu.service.ShopService;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

@Api(description = "运营模式配置")
@RestController
public class RunModelController implements Tools {
    private static Logger logger = LoggerFactory.getLogger(RunModelController.class);

    @ApiOperation(value = "创建运营模式")
    @PostMapping(value = ("/run/model"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true, checkShopId = true, companyUser = true)
    public ResponseData create(@RequestBody RunModel runModel) throws Exception {
        VerifyUtil.verify(() -> runModel.getShopId() != null);
        return CommonService.getInstance().createObject(runModel);
    }

    @ApiOperation(value = "查询运营模式")
    @PutMapping(value = ("/run/model"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(mustLogin = false)
    public ResponseData query(@RequestBody RunModel runModel) throws Exception {
        return CommonService.getInstance().searchResponse(runModel);
    }

    @ApiOperation(value = "修改运营模式")
    @PutMapping(value = ("/run/model/modify"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShopId = true)
    public ResponseData modify(@RequestBody RunModel runModel) throws Exception {
        CommonService commonService = CommonService.getInstance();
        RunModel runModelInDb = commonService.findEntity(runModel.getId(), RunModel.class);
        VerifyUtil.verify(() -> runModelInDb != null);
        Long shopId = runModelInDb.getShopId();
        Shop shop = ShopService.getInstance().findShopById(shopId);

        return CommonService.getInstance().updateObject(runModel, null, (t) -> {
            try {
                return RunModelService.getInstance().checkRunModel(t);
            } catch (Exception e) {
                logger.info("e", e);
                return ResponseStatus.SYSTEM_ERROR;
            }
        }, null);
    }


    @ApiOperation(value = "删除运营模式")
    @DeleteMapping(value = ("/run/model"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true, companyUser = true)
    public ResponseData delete(@RequestBody RunModel runModel) throws Exception {
        return CommonService.getInstance().delete(runModel);
    }
}
